from datetime import datetime
from os import makedirs
from os.path import splitext
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import Event
from nonebot.permission import USER, Permission
from nonebot.plugin import on_notice
from nonebot.typing import T_State
from requests import get
from ...dao.class_student_dao import get_stu_class

from ...dao.submit_record_dao import modify_record

from ...dao import assignment_dao, group_dao
from ...dao.user_dao import get_stu
from ...utils.utils import get_options_list


async def _stu_id_checker(bot: Bot, event: Event, state: T_State) -> bool:
    # logger.opt(colors=True).info(f"名单：{event}")
    is_file = bool(event.notice_type == "offline_file")
    is_send_by_teacher = str(event.user_id) in bot.config.superusers
    return is_file and not is_send_by_teacher


async def _permission_updater(
        bot: Bot, event: Event, state: T_State, permission: Permission) -> Permission:
    try:
        new_permission = USER(event.get_session_id(), perm=permission)
    except ValueError:
        new_permission = USER(str(event.user_id), perm=permission)
    return new_permission


submit_assignment = on_notice(rule=_stu_id_checker, priority=1, block=True)
submit_assignment._default_permission_updater = _permission_updater


@submit_assignment.handle()
async def submit_assignment_handler(bot: Bot, event: Event, state: T_State):
    state["file"] = event.file
    state["qq_id"] = event.user_id
    try:
        _,stu_id,stu_name = await get_stu(state['qq_id'])
    except Exception:
        await submit_assignment.finish("该QQ号尚未与学号绑定！")
    state["stu_id"],state["stu_name"] = stu_id,stu_name
    gid_list = await get_stu_class(stu_id)
    gid_list = list(map(lambda x: x[0],gid_list))
    cls_list = await group_dao.getAllClass(bot)
    cls_list = list(filter(lambda x: x.gid in gid_list,cls_list))
    cls_options = get_options_list(list(map(lambda x: x.name, cls_list)))
    state["cls_list"] = cls_list
    state["class_count"] = len(cls_list)
    
    if cls_options == '':
        await submit_assignment.finish("你尚未加入任何班级！")
    await submit_assignment.send(cls_options)
    await submit_assignment.send("你想提交哪个班级的作业呢？")

@submit_assignment.receive()
async def handle_class_no(bot: Bot, event: Event, state: T_State):
    state["class_no"] = str(event.get_message()).strip()
    # logger.info(event)
    try:
        num = int(state["class_no"])
    except ValueError:
        await submit_assignment.reject("请输入数字！")

    if num < 0 or state["class_count"] <= num:
        await submit_assignment.reject("请输入在{}到{}之间的数字！".format(0, state["class_count"] - 1))
    
    assignment_list = await assignment_dao.getAssignmentOfClass(state["cls_list"][num].gid,1)
    state["assignment_list"] = assignment_list
    state["assignment_count"] = len(assignment_list)
    if(len(assignment_list) == 0):
        await submit_assignment.finish("当前班级没有可以提交的作业！")
    if(len(assignment_list) == 1):
        state["assignment_no"] = 0
    else:
        assign_options = get_options_list(list(map(lambda x: x[2], assignment_list)))
        await submit_assignment.send(assign_options)

@submit_assignment.got('assignment_no',"你想提交哪次作业呢？")
async def handle_assignment_no(bot: Bot, event: Event, state: T_State):
    state["assignment_no"] = str(event.get_message()).strip()
    # logger.info(event)
    try:
        num = int(state["assignment_no"])
    except ValueError:
        await submit_assignment.reject("请输入数字！")

    if num < 0 or state["assignment_count"] <= num:
        await submit_assignment.reject("请输入在{}到{}之间的数字！".format(0, state["assignment_count"] - 1))
    
    now = int(round(datetime.now().timestamp() * 1000))
    end_time = state["assignment_list"][num][3]
    # logger.info(f"截止时间：{end_time}")
    if(now > end_time):
        await submit_assignment.finish("无法提交！现在已经过了本次作业的截止时间")
    

@submit_assignment.handle()
async def handle_assignment(bot: Bot, event: Event, state: T_State):
    file: dict = state["file"]
    curr_assign = state["assignment_list"][int(state["assignment_no"])]
    gid,assign_id,assign_name = curr_assign[1],curr_assign[0],curr_assign[2]
    stu_id,stu_name = state["stu_id"],state["stu_name"]
    download_assignment = get(file['url'], allow_redirects=True)
    makedirs(f"static/{gid}/{assign_id}",exist_ok=True)
    if bot.config.rename_assgin:
        extension_name = splitext(file['name'])[1]
        with open("static/{}/{}/{}_{}_{}{}"
        .format(gid,assign_id,stu_id,stu_name,assign_name,extension_name), 'wb') as f:
            f.write(download_assignment.content)
    else:
        with open(f"static/{gid}/{assign_id}/{file['name']}", 'wb') as f:
            f.write(download_assignment.content)

    await modify_record(assign_id,stu_id)
    await submit_assignment.finish("作业提交成功！")